package com.resolution.dietaryassessment.view.tcm.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;

import com.example.rxbus.RxBus;
import com.example.rxbus.bean.MsgEvent;
import com.example.rxbus.bean.TCMEvent;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.resolution.dietaryassessment.R;
import com.resolution.dietaryassessment.utils.FragAndActivityCommunication;
import com.resolution.dietaryassessment.view.tcm.bean.TCMEnum;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.internal.operators.flowable.FlowableOnErrorReturn;
import io.reactivex.plugins.RxJavaPlugins;

import static android.content.ContentValues.TAG;
import static com.resolution.dietaryassessment.view.tcm.bean.TCMEnum.*;

/**
 * @author By Resolusion
 * @Title:
 * @Date: 2020/3/30
 * @Time: 16:01
 * @email Res01ution@foxmail.com
 */
public class TcmResultFragment extends Fragment {
    @BindView(R.id.barChar)
    BarChart barChar;
    @BindView(R.id.peace_btn)
    Button peaceBtn;
    @BindView(R.id.qi_deficiency_btn)
    Button qiDeficiencyBtn;
    @BindView(R.id.yang_deficiency_btn)
    Button yangDeficiencyBtn;
    @BindView(R.id.yin_deficiency_btn)
    Button yinDeficiencyBtn;
    @BindView(R.id.phlegm_damp_btn)
    Button phlegmDampBtn;
    @BindView(R.id.damp_heat_btn)
    Button dampHeatBtn;
    @BindView(R.id.blood_stasis_btn)
    Button bloodStasisBtn;
    @BindView(R.id.qi_depression_btn)
    Button qiDepressionBtn;
    @BindView(R.id.special_gift_btn)
    Button specialGiftBtn;
    @BindView(R.id.major_tx)
    TextView majorTx;
    @BindView(R.id.minor)
    TextView minor;

    private Unbinder unbinder;
    private FragAndActivityCommunication callback;

    private View view;

    private BarDataSet dataSet;
    private BarData data;
    private List<BarEntry> barEntryList = new ArrayList<>();
    private List<String> mXAxisNameList = new ArrayList<>();

    private static final int PEACE_CODE = 0;
    private static final int QIXU_CODE = 1;
    private static final int YANGXU_CODE = 2;
    private static final int YINXU_CODE = 3;
    private static final int TANSHI_CODE = 4;
    private static final int SHIRE_CODE = 5;
    private static final int XUEYU_CODE = 6;
    private static final int QIYU_CODE = 7;
    private static final int TEBING_CODE = 8;


    public static TcmResultFragment getInstance() {
        TcmResultFragment trf = new TcmResultFragment();
        Bundle bundle = new Bundle();
        trf.setArguments(bundle);
        return trf;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        callback = (FragAndActivityCommunication) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tcm_result, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initBarEntries();
        return view;
    }

    private void initView() {
        Collections.addAll(mXAxisNameList, PEACE.getName(), QIXU.getName(),
                YANGXU.getName(), YINXU.getName(), TANSHI.getName(),
                SHIRE.getName(), XUEYU.getName(), QIYU.getName(), TEBING.getName());
    }

    /**
     * 初始化统计图
     */
    private void initBarChartView() {
        //清除点击
        barChar.setTouchEnabled(false);
        barChar.setMaxVisibleValueCount(100);
        //清除右下角legend
        barChar.getLegend().setEnabled(false);
        //清除Description
        barChar.getDescription().setEnabled(false);

        XAxis xAxis = barChar.getXAxis();
        //view的长度不能超过list的长度
        xAxis.setLabelCount(mXAxisNameList.size(), false);
        //清除X轴网格线
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        //X在下方
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setValueFormatter(XAxisCustom(mXAxisNameList));

        YAxis leftAxis = barChar.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        leftAxis.setLabelCount(5, false);
        //设置Y轴最小坐标和最大坐标
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(100f);

        //清除右边Y轴
        barChar.getAxisRight().setEnabled(false);


        dataSet = new BarDataSet(barEntryList, "中医体质统计图");
        data = new BarData(dataSet);
        dataSet.setColors(Color.parseColor("#feb64d"), Color.parseColor("#ff7c7c"),
                Color.parseColor("#9287e7"),
                Color.parseColor("#60acfc"));
        barChar.setData(data);
        barChar.invalidate();
    }

    @SuppressLint("CheckResult")
    private void initBarEntries() {
        RxBus.getInstance().toObservable(getActivity(), TCMEvent.class, Lifecycle.Event.ON_ANY)
                .subscribe(msgEvent -> {
                    List<Float> scoreList;
                    scoreList = (List<Float>) msgEvent.getObj();
                    Log.d(TAG, "initBarEntries: " + scoreList);
                    BarEntry barEntry1 = new BarEntry(PEACE.getIndex(), scoreList.get(PEACE.getIndex()));
                    BarEntry barEntry2 = new BarEntry(QIXU.getIndex(), scoreList.get(QIXU.getIndex()));
                    BarEntry barEntry3 = new BarEntry(YANGXU.getIndex(), scoreList.get(YANGXU.getIndex()));
                    BarEntry barEntry4 = new BarEntry(YINXU.getIndex(), scoreList.get(YINXU.getIndex()));
                    BarEntry barEntry5 = new BarEntry(TANSHI.getIndex(), scoreList.get(TANSHI.getIndex()));
                    BarEntry barEntry6 = new BarEntry(SHIRE.getIndex(), scoreList.get(SHIRE.getIndex()));
                    BarEntry barEntry7 = new BarEntry(XUEYU.getIndex(), scoreList.get(XUEYU.getIndex()));
                    BarEntry barEntry8 = new BarEntry(QIYU.getIndex(), scoreList.get(QIYU.getIndex()));
                    BarEntry barEntry9 = new BarEntry(TEBING.getIndex(), scoreList.get(TEBING.getIndex()));
                    Collections.addAll(barEntryList, barEntry1, barEntry2, barEntry3, barEntry4, barEntry5,
                            barEntry6, barEntry7, barEntry8, barEntry9);

                    initBarChartView();

                    /*
                     * 获取统计信息
                     */
                    List<Integer> list = new ArrayList<>();
                    float scoreMax = scoreList.get(0);
                    int maxScoreIndex = 0;
                    for (int i = 0; i < scoreList.size(); i++) {
                        if (scoreList.get(i) > scoreMax) {
                            scoreMax = scoreList.get(i);
                            maxScoreIndex = i;
                        }
                        if (scoreList.get(i) >= 50) {
                            list.add(i);
                        }
                    }
                    System.out.println("list成绩最大的是：" + scoreMax + " .... " + maxScoreIndex);
                    minor.setText("兼有体质：".concat(getName(list,maxScoreIndex)));

                    switch (maxScoreIndex) {
                        case PEACE_CODE:
                            majorTx.setText(PEACE.getName());
                            break;
                        case QIXU_CODE:
                            majorTx.setText(QIXU.getName());
                            break;
                        case YANGXU_CODE:
                            majorTx.setText(YANGXU.getName());
                            break;
                        case YINXU_CODE:
                            majorTx.setText(YINXU.getName());
                            break;
                        case TANSHI_CODE:
                            majorTx.setText(TANSHI.getName());
                            break;
                        case SHIRE_CODE:
                            majorTx.setText(SHIRE.getName());
                            break;
                        case XUEYU_CODE:
                            majorTx.setText(XUEYU.getName());
                            break;
                        case QIYU_CODE:
                            majorTx.setText(QIYU.getName());
                            break;
                        case TEBING_CODE:
                            majorTx.setText(TEBING.getName());
                            break;
                    }
                });
    }

    /**
     * 自定义X轴
     */
    private IAxisValueFormatter XAxisCustom(List<String> list) {
        return new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return list.get((int) value);
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        };
    }

    @SuppressLint("ResourceType")
    @OnClick({R.id.peace_btn, R.id.qi_deficiency_btn, R.id.yang_deficiency_btn,
            R.id.yin_deficiency_btn, R.id.phlegm_damp_btn, R.id.damp_heat_btn,
            R.id.blood_stasis_btn, R.id.qi_depression_btn, R.id.special_gift_btn})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.peace_btn:
                startLa(peaceBtn.getText().toString());
                break;
            case R.id.qi_deficiency_btn:
                startLa(qiDeficiencyBtn.getText().toString());
                break;
            case R.id.yang_deficiency_btn:
                startLa(yangDeficiencyBtn.getText().toString());
                break;
            case R.id.yin_deficiency_btn:
                startLa(yinDeficiencyBtn.getText().toString());
                break;
            case R.id.phlegm_damp_btn:
                startLa(phlegmDampBtn.getText().toString());
                break;
            case R.id.damp_heat_btn:
                startLa(dampHeatBtn.getText().toString());
                break;
            case R.id.blood_stasis_btn:
                startLa(bloodStasisBtn.getText().toString());
                break;
            case R.id.qi_depression_btn:
                startLa(qiDepressionBtn.getText().toString());
                break;
            case R.id.special_gift_btn:
                startLa(specialGiftBtn.getText().toString());
                break;
            default:
        }
    }

    private void startLa(String str){
        RxBus.getInstance().post(new MsgEvent(str));
        callback.onNextFragment(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
